package com.example.multithread;

import java.util.concurrent.atomic.AtomicLongFieldUpdater;

class Book2 {
    // 需要同步修改的属性，必须使用 volatile 关键字修饰
    volatile long id;
    private String title;
    private double price;

    public Book2(long id, String title, double price) {
        this.id = id;
        this.title = title;
        this.price = price;
    }

    public long getId() {
        return id;
    }

    public void setId(long id) {
        AtomicLongFieldUpdater updater = AtomicLongFieldUpdater.newUpdater(Book2.class, "id");
        updater.compareAndSet(this, this.id, id);
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book2{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", price=" + price +
                '}';
    }
}

public class FieldUpdaterTest {
    public static void main(String[] args) {
        Book2 book2 = new Book2(1, "Java", 9.9);
        book2.setId(2);
        System.out.println(book2);
    }
}
